package com.web.tree;

import java.util.LinkedList;
import java.util.Queue;

public class TreePrint {
	
	public void print(BinaryTree root) {
		//创建一个队列用来存放节点
		Queue<BinaryTree> queue = new LinkedList<BinaryTree>();
		//当前行打印的最右节点
		BinaryTree last;
		//下一行打印的最右节点
		BinaryTree nlast = null;
		last = root;
		//先将根放入队列中
		queue.add(root);
		while (queue.size() > 0) {
			//推出节点
			BinaryTree nowTree = queue.poll();
			//如果当前节点有左节点，将左节点压入队列
			if (nowTree.hasLeftNode()) {
				queue.add(nowTree.getLeftNode());
				nlast = nowTree.getLeftNode();
			}
			//如果当前节点有右节点，将右节点压入队列
			if (nowTree.hasRightNode()) {
				queue.add(nowTree.getRightNode());
				nlast = nowTree.getRightNode();
			}
			
			System.out.print("      "+nowTree.getValue());
			
			//当当前打印节点为当前行最右节点时换行
			if (last.equals(nowTree)) {
				System.out.println();
				last = nlast;
			}
		}
	}

	public static void main(String[] args) {
		BinaryTree root = new BinaryTree();
        root.setValue("root");
        BinaryTree left01 = new BinaryTree("left01");
        BinaryTree right01 = new BinaryTree("right01");
        root.setLeftNode(left01);
        root.setRightNode(right01);
        BinaryTree left11 = new BinaryTree("left11");
        BinaryTree right11 = new BinaryTree("right11");
        left01.setLeftNode(left11);
        left01.setRightNode(right11);
        BinaryTree left12 = new BinaryTree("left12");
        BinaryTree right12 = new BinaryTree("right12");
        right01.setLeftNode(left12);
        right01.setRightNode(right12);
        TreePrint print = new TreePrint();
        print.print(root);
	}
}
